const fs = require('fs');
const vm = require('vm');
const path = require('path');
const Knex = require('knex');

let db;

exports.dbInit = (opts = {}) => {
  try {
    db = Knex({
      client: 'mysql',
      connection: {
        timezone: '+08:00',
        host: opts.host,
        port: opts.port,
        user: opts.user,
        password: opts.password,
        database: opts.database,
        charset: opts.charset,
        dateStrings: true,
      },
      pool: {
        min: 3,
        max: 10,
      },
      debug: process.env.DEV === 'true',
    });
    global._db = db;
    global._db.model = {};
    setModels(global._db);
    global._logger.info('::: default db init success:');
  } catch (error) {
    global._logger.error('::: default db init error', error);
  }
};

function setModels(db) {
  const modelRoot = path.join(path.dirname(__dirname), 'models');
  const fileList = fs.readdirSync(modelRoot);
  fileList.forEach(tablename => {
    const abspath = path.join(modelRoot, tablename);
    if (/\.js$/.test(tablename) && !/^\./.test(tablename)) {
      try {
        const sourceCode = fs.readFileSync(abspath);
        new vm.Script(sourceCode); // check syntax
        db.model[tablename.replace('.js', '')] = require(abspath);
        _logger.info('models load success :::', tablename);
      } catch (e) {
        global._logger.error(`${abspath} syntax error:${e.message}`);
      }
    }
  });
}
